package cn.wolfcode.luowowo.website.web.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //该解析器支持解析的参数类型
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果返回true,则是表示支持对应的类型
        //当参数类型是userInfo并且贴有UserParam注解时,才会返回true,然后执行第二个方法
        //boolean b = parameter.getParameterType() == UserInfo.class;
        //boolean b1 = parameter.hasParameterAnnotation(UserParam.class);
        return parameter.getParameterType() == UserInfo.class &&
                parameter.hasParameterAnnotation(UserParam.class);
    }

    //解析器解析规则
    //此处将token 转换成userInfo对象
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

        String token = CookieUtil.getToken(request, response);
        String userStr = userInfoRedisService.getToken(token);
        UserInfo user = JSON.parseObject(userStr, UserInfo.class);
       // System.out.println(user);
        return user;
    }
}
